<template>
  <div class="login-container">
    <el-card class="login-card" style="margin: 20;">
      <h2 class="login-title">用户管理系统</h2>
      <form @submit.prevent="handleLogin" method="post" action="http://localhost:8088/token">
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            class="login-button"
            :loading="loading"
          >登录</el-button>
        </el-form-item>
      </el-form>
      </form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'



const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = ref({
  username: '',
  password: ''
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = () => {
  loginFormRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      const formData = new FormData()
      formData.append('username', loginForm.value.username)
      formData.append('password', loginForm.value.password)
      formData.append('grant_type', 'password')
      axios.post(`/api/token`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        if (response.data && response.data.access_token) {
          loading.value = false
          ElMessage.success('登录成功')
          localStorage.setItem('token', response.data.access_token)
          router.push('/home')
        } else {
          loading.value = false
          ElMessage.error('登录失败：无效的响应')
        }
      })
      .catch(error => {
        loading.value = false
        ElMessage.error(error.response?.data?.message || '登录失败')
      })
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  /* width: 100vw; */
  background-color: #f5f7fa;
  overflow: hidden;
}
.login-card {
  width: 400px;
  padding: 20px;
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
.login-button {
  width: 100%;
}
</style>